package com.anita.member.domain.model.member;

import com.anita.member.common.exception.BusinessException;

import java.util.regex.Pattern;

/**
 * 邮箱值对象
 * @author qiu
 * @date 2025/10/17
 * @description
 */
public record Email (String value){

    private static final Pattern PATTERN = Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");

    public Email(String value) {
        if(value == null || value.trim().isEmpty()){
            throw new BusinessException("会员邮箱不能为空");
        }
        String trimmed = value.trim().toLowerCase();
        if(!PATTERN.matcher(trimmed).matches()){
            throw new BusinessException("会员邮箱格式不正确");
        }
        this.value = trimmed;
    }

    public static Email of(String s) {
        return new Email(s);
    }

    /**
     * 获取邮箱域名
     * @return
     */
    public String domain() {
        int idx = value.indexOf('@');
        return value.substring(idx + 1);
    }

    public String getValue() {
        return value;
    }
}
